package com.android.lovely.ui.viewmodel

import android.os.SystemClock
import androidx.lifecycle.viewModelScope
import com.android.lovely.api.service.userService
import com.android.lovely.framework.BaseViewModel
import com.android.lovely.manager.UpLoadRoleManager
import com.android.lovely.room.role.CacheRoleServer
import com.android.lovely.room.role.CreateRole
import com.android.lovely.room.role.CreateRoleDataBase
import com.android.lovely.room.role.NewCard
import com.kotlin.extensions.coroutine.CoroutineExt.launchSafety
import org.json.JSONObject

/**
 *
 * @author why
 * @date 2025/4/8 11:41
 */
class CreateRolePreviewViewModel : BaseViewModel() {

    private val creator get() = createRole?.let { UpLoadRoleManager(it) }


    suspend fun createRole(): Boolean = creator?.executeCreation() ?: false

    var id = SystemClock.elapsedRealtime().toInt()

    var createRole: CreateRole? = null



    fun updateRole(updateAction: CreateRole.() -> Unit) {
        viewModelScope.launchSafety {
            createRole?.updateAction()
            createRole?.let {
                CacheRoleServer.update(it)
                CreateRoleDataBase.dao.save(it)
            }
        }
    }

    fun getCard(id: Int) {
        viewModelScope.launchSafety {
            val role = CreateRoleDataBase.dao.getRole(id)
            if ((role?.createId ?: 0) > 0) {
                val cards = userService.getDraftCards(mapOf("id" to id)).cardList
                updateRole {
                    this.cards = cards.map {
                        var width = 0
                        var height = 0
                        runCatching {
                            val json = JSONObject(it.imgDetail)
                            width = json.optInt("width")
                            height = json.optInt("height")
                        }
                        NewCard(url = it.imgUrl, width = width, height = height, id = it.id)
                    }
                }
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        creator?.remove()
    }
}